package com.btpn.custody.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.btpn.custody.dao.IAddress;
import com.btpn.custody.entity.Address;

@Repository("addressDaoHibernate")
public class AddressDAO implements IAddress {

	protected HibernateTemplate template = null;
	
	@Autowired @Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	@Override
	public Address get(Long id) {
		return template.get(Address.class, id);
	}
	
	@Override
	public List<Address> findAll() {
		return template.loadAll(Address.class);
	}
	
	@Override
	public Integer getCount() {
		return Integer.valueOf(findAll().size());
	}
	
	@Override
	public Serializable create(Address address) {
		return template.save(address);
	}

	@Override
	public Address update(Address address) {
		template.update(address);
		
		return address;
	}

	@Override
	public void createOrUpdate(Address address) {
		template.saveOrUpdate(address);
	}
	
	@Override
	public void delete(Long id) {
		template.delete(get(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Address getByMD_AddressType(String mdSid, String addressType) {
		List<Address> result = template.findByNamedQueryAndNamedParam(Address.NQ__GET_BY_MD_AND_ADDRESS_TYPE, 
				new String[] { "mdSid", "addressType" }, new Object[] { mdSid, addressType });
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Address> findByMD(String mdSid) {
		return template.findByNamedQueryAndNamedParam(Address.NQ__FIND_BY_MD, new String[] { "mdSid" }, new Object[] { mdSid });
	}
}